
<!-- switch 开关组件 -->
<template>
  <div class="picker-select">
    <input :value="value" :placeholder="placeholder" onfocus="this.blur()" @click="showPick = !showPick" readonly="readonly" />
    <div class="modal" v-if="showPick" @click="cancel"></div>
    <div class="picker-con" v-show="showPick">
      <div class="picker-title">
        <div class="cancel" @click="cancel">取消</div>
        <div class="sure" @click="sure">完成</div>
      </div>
      <mt-picker :visibleItemCount="5" :itemHeight="36" :slots="selectList" @change="countryChange"></mt-picker>
    </div>
  </div>
</template>
<script>
import Vue from 'vue'
import { Picker } from 'mint-ui';
Vue.component(Picker.name, Picker);

export default {
  model: {
    prop: 'value',
    event: 'change'
  },
  data() {
    return {
      showPick: false,
      nowValue: '',
    }
  },
  components: {
    Picker
  },
  props: {
    list: {
      type:Array,
      default:[]
    },
    value:{
      type: String,
      default: '',
    },
    placeholder: {
      type: String,
      default: '',
    },
  },
  watch:{
    showPick(n,o){
      if(n){
        //打开模态框前调用
        var scrollTop = document.body.scrollTop || document.documentElement.scrollTop;
        document.body.style.cssText += 'position:fixed;top:-' + scrollTop + 'px;';
      }else{
       this.closePick();
      }
    }
  },
  computed: {
    selectList () {
      if(this.default && this.list.length) {
        let defaultIndex = 0
        this.list.values.filter((item)=> {
          if(item == this.default) {
            defaultIndex = item;
          }
        })
        this.list[0].defaultIndex = defaultIndex;
      }
      return this.list;
    }
  },
  destroyed(){
    this.closePick();
  },
  methods: {
    //关闭模态框后调用
    closePick(){
       var body = document.body;
      body.style.position = 'static';
      var top = body.style.top;
      document.body.scrollTop = document.documentElement.scrollTop = -parseInt(top);
      body.style.top = '';
    },
    //值改变的时候
    countryChange (picker, values) {
      this.nowValue = values[0];
    },
    cancel () {
      this.nowValue = this.value;
      this.showPick = false;
    },
    sure () {
      this.showPick = false;
      this.value = this.nowValue;
      this.$emit('change', this.nowValue);
    }
  }
}
</script>
<style lang="less" scoped>
.modal {
  position:fixed;
  top:0;
  left:0;
  bottom:0;
  right:0;
  background:rgba(0,0,0,.7);
  z-index:10001;
}
.picker-con{
  width: 100%;
  position: fixed;
  left: 0;
  bottom: 0;
  z-index: 100000;
  background: #fff;
  border-top: 2px solid #edeef0;

  .picker-title {
    line-height: 90px;
    display: flex;
    -webkit-box-pack: justify;
    justify-content: space-between;

    div {
      padding: 0 60px;
      color: #2086f9;
      font-size: 32px;
    }
  }
}
</style>
